﻿using QuickLogin.Connect;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace QuickLogin
{
    public partial class frmMain : Form
    {
        User DefaultUser = null;
        public frmMain()
        {
            InitializeComponent();
            lbVersion.Text = Application.ProductVersion;
            if (Application.ProductVersion == "9.9.9.9")
            {
                cbxShowPassWord.Visible = false;
            }
            //启动守护线程 
            DaemonThreadExt.Start((t, v) => this.Invoke(new CallBacDelegate(CallBack), new Object[] { t, v }));
        }
        public delegate void CallBacDelegate(ConnectType p_Type, object p_str);

        void CallBack(ConnectType p_Type, object p_Value)
        {
            try
            {
                switch (p_Type)
                {
                    //新闻
                    case ConnectType.GetNewsSuccess:
                        #region
                        Font fTitle = new Font("Verdana", 9, FontStyle.Bold);
                        Font fDes = new Font("Verdana", 8);
                        foreach (var news in (List<News>)p_Value)
                        {
                            // Title
                            txtNews.SelectionAlignment = HorizontalAlignment.Left;
                            txtNews.SelectionColor = news.Color;
                            txtNews.SelectionFont = fTitle;
                            txtNews.AddLine(news.Title);
                            //描述
                            txtNews.AddLine("\t" + news.Description);

                            //txtNews.SelectionAlignment = HorizontalAlignment.Center;
                            txtNews.SelectionColor = Color.Green;
                            txtNews.AppendText(news.Pubdate + " ");
                            //Link 
                            txtNews.SelectionAlignment = HorizontalAlignment.Right;
                            txtNews.InsertLink("More", news.Link);
                            txtNews.AddLine("");
                        }
                        txtInfo.AddLine("获取新闻成功.");
                        #endregion
                        break;
                    //获得数据中心
                    case ConnectType.GetDataCenterSuccess:
                        #region
                        var _worlds = (List<World>)p_Value;
                        if (_worlds != null)
                        {
                            cblServerList.DisplayMember = "Name";
                            cblServerList.Items.Clear();
                            foreach (World world in _worlds)
                            {
                                cblServerList.Items.Add(world);
                                if (DefaultUser != null)
                                {
                                    if (world.Name == DefaultUser.WorldName) cblServerList.SelectedItem = world;
                                }
                                else if (world.Name == "Sarlona")
                                {
                                    cblServerList.SelectedItem = world;
                                }
                            }
                            txtInfo.AddLine("服务器状态获取成功.");
                        }
                        SetLoginEnable(true);
                        #endregion
                        break;
                    //用户信息读取成功
                    case ConnectType.UserListChange:
                        #region
                        var userLists = (UserList)p_Value;
                        if (userLists.AllUser != null && userLists.AllUser.Count > 0)
                        {
                            cblUsername.Items.Clear();
                            foreach (User user in userLists.AllUser)
                            {
                                cblUsername.Items.Add(user);
                            }
                            if (userLists.DefaultUser != null)
                            {
                                cblUsername.SelectedItem = userLists.DefaultUser;
                                txtPassword.Text = userLists.DefaultUser.PassWord;
                            }
                            DefaultUser = userLists.DefaultUser;
                            txtInfo.AddLine("账户信息读取成功.");
                        }
                        SetUserEnable(true);
                        #endregion
                        break;
                    //服务器配置获取成功
                    case ConnectType.GetConfigSuccess:
                        #region
                        var linkDic = (Dictionary<string, string>)p_Value;
                        foreach (var name in linkDic.Keys)
                        {
                            pnlLink.Controls.Add(NewLinkLabel(name, linkDic[name]));
                        }
                        pnlLink.Controls.Add(NewLinkLabel("贴吧", "https://tieba.baidu.com/f?kw=%E9%BE%99%E4%B8%8E%E5%9C%B0%E4%B8%8B%E5%9F%8E&ie=utf-8"));
                        pnlLink.Controls.Add(NewLinkLabel("WiKi", "http://ddowiki.com/"));
                        pnlLink.Controls.Add(NewLinkLabel("源码", "https://gitee.com/dlanny/DDO_QuickLogin"));
                        pnlLink.Controls.Add(NewLinkLabel("模拟器", "http://dlanny.gitee.io/ddo_quicklogin/"));
                        txtInfo.AddLine("服务器配置获取成功.");
                        #endregion
                        break;
                    //登陆事件
                    case ConnectType.LoginFaild:
                    case ConnectType.LoginSuccess:
                        txtInfo.AddLine(p_Value);
                        if (p_Type == ConnectType.LoginFaild)
                        {
                            MessageBox.Show(p_Value.ToString());
                        }
                        SetLoginEnable(true);
                        break;
                    //普通消息
                    case ConnectType.Message:
                        txtInfo.AddLine(p_Value);
                        break;
                    default:
                        break;
                }
            }
            catch (Exception exx)
            {
                MessageBox.Show(exx.Message);
            }
        }
        Label NewLinkLabel(string txt, string Url)
        {
            Label lbLink = new Label();
            lbLink.Cursor = Cursors.Hand;
            lbLink.AutoSize = true;
            lbLink.BackColor = Color.Transparent;
            lbLink.Font = new Font("Microsoft YaHei UI", 18F, FontStyle.Regular, GraphicsUnit.Pixel);
            lbLink.ForeColor = Color.White;
            lbLink.Text = txt;
            lbLink.Click += new EventHandler((o, e) => OpenUrl(Url));
            return lbLink;
        }


        void SetUserEnable(bool isEnable)
        {
            cblUsername.Enabled = isEnable;
            cbxRemember.Enabled = isEnable;
            cbxShowPassWord.Enabled = isEnable;
            txtPassword.Enabled = isEnable;
        }

        void SetLoginEnable(bool isEnable)
        {
            btnLogin.Enabled = isEnable;
            btnLoginX64.Enabled = isEnable;
            btnUpdate.Enabled = isEnable;
            cblServerList.Enabled = isEnable;
        }

        /// <summary>
        /// 下拉框选项改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cblUsername_TextChanged(object sender, EventArgs e)
        {
            try
            {
                txtPassword.Text = string.Empty;
                foreach (User user in cblUsername.Items)
                {
                    if (user.UserName == cblUsername.Text)
                    {
                        txtPassword.Text = user.PassWord;
                        foreach (World world in cblServerList.Items)
                        {
                            if (world.Name == user.WorldName)
                            {
                                cblServerList.SelectedItem = world;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        /// <summary>
        /// 调用官方客户端更新游戏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                if (File.Exists("DNDLauncher.exe"))
                {
                    Process.Start(new ProcessStartInfo("DNDLauncher.exe", " -invoker -nosplash -skiprawdownload "));
                }
                else MessageBox.Show("找不到DNDLauncher.exe文件!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        /// <summary>
        /// 显示密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CbxShowPassWord_CheckedChanged(object sender, EventArgs e) => txtPassword.UseSystemPasswordChar = !cbxShowPassWord.Checked;
        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClose_Click(object sender, EventArgs e) => Application.Exit();
        /// <summary>
        /// 最小化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMin_Click(object sender, EventArgs e) => this.WindowState = FormWindowState.Minimized;
        //界面拖动
        private Point mousePoint;
        private Point formPoint;
        /// <summary>
        /// 鼠标按下
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void MouseDownEvent(object sender, MouseEventArgs e)
        {
            mousePoint = Control.MousePosition;
            formPoint = this.Location;
        }
        /// <summary>
        /// 鼠标移动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void MouseMoveEvent(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Point mousePos = Control.MousePosition;
                this.Location = new Point(mousePos.X - mousePoint.X + formPoint.X, mousePos.Y - mousePoint.Y + formPoint.Y);
            }
        }
        /// <summary>
        /// 新闻中的链接点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtInfo_LinkClicked(object sender, LinkClickedEventArgs e)
        {
            if (e.LinkText.IndexOf('#') > 0 && e.LinkText.Split('#').Length > 1)
            {
                OpenUrl(e.LinkText.Split('#')[1]);
            }
        }

        /// <summary>
        /// 调用默认浏览器打开链接
        /// </summary>
        /// <param name="p_strUrl"></param>
        private void OpenUrl(string p_strUrl)
        {
            try
            {
                if (string.IsNullOrEmpty(p_strUrl)) return;
                Process.Start(p_strUrl);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        /// <summary>
        /// 使用64位客户端登陆
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLoginX64_Click(object sender, EventArgs e) => Login(ClientType.X64);
        /// <summary>
        /// 使用32位客户端登陆
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLogin_Click(object sender, EventArgs e) => Login(ClientType.X86);
        /// <summary>
        /// 使用后台线程开启DDO客户端
        /// </summary>
        /// <param name="clientType"></param>
        private void Login(ClientType clientType)
        {
            try
            {
                SetLoginEnable(false);
                var world = (World)cblServerList.SelectedItem;
                User user = new User()
                {
                    PassWord = txtPassword.Text.Trim(),
                    UserName = cblUsername.Text.Trim(),
                    WorldName = world.Name,
                    WorldStatusServerUrl = world.StatusServerUrl,
                    ChatServerUrl = world.ChatServerUrl,
                    ClientType = clientType
                };
                //登陆前检查
                if (!user.CheckCanLogin(out string msg))
                {
                    MessageBox.Show(msg);
                    SetLoginEnable(true);
                }
                else
                {
                    DaemonThreadExt.Login(user);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                SetLoginEnable(true);
            }
        }
    }
}